public with sharing class KAForKAResourceAllcationController {
     public String OutletName{get;set;}
     public String KASelectedValue{get;set;}
     public Activity_Information__c ActivityInit{get;set;}
     public CommonAttribute PlaceAttribute{get;set;}
     public List<ActivityCompetitionBrandEntry> CompetitionBrandList{get;set;}//竞品信息
     public Boolean IsSelectedAllCompetition{get;set;}//竟品费用全选
     public string CompetitorOtletName{get;set;}
     public List<Activity_Competition_Brand_Detail__c> CompetitionBrandDetailList{get;set;}
     public List<String> ColumnETList{get;set;}
     public List<String> ColumnFGList{get;set;}
     public Set<String> OutletColumnList{get;set;}
     public Integer Rows{get;set;}
     public  List<DynamicColumnEntry> ETDynamicColumnEntryList{get;set;}
     public  List<DynamicColumnEntry> FGDynamicColumnEntryList{get;set;}
     public Boolean WhetherDisplaySubmitOrSaveButtonOrNot{get;set;}//按钮是否可用
     public List<CityResourceAllcation__c> ETresourceDetailList;//ET资源明细
     public List<CityResourceAllcation__c> FGresourceDetailList;//FG资源明细
     public CommonMethod getCommonMethod;
     public List<SelectOption> KAList{get;set;}
     Transient  public Blob GetFileValue{get;set;}//导入进来的文件
     public decimal TotalMoney{get;set;}
     public String SSYPromotionTypeSelectedValue{get;set;}
     public String SSYKACostTypeSelectedValue{get;set;}
     public String CostSourceSelectedValue{get;set;}
    //ET资源
      public List<AllocationResourceEntry> ETResourceEntryList
     {
         get
         {
           String filter=' and KAName__c=\''+KASelectedValue+'\' and Type__c=\'ET\'';
               
               return getCommonMethod.LoadResourceAllcationListByCity(filter,RecordId);
               
         }
     }
     //FG资源
       public List<AllocationResourceEntry> FGResourceEntryList
     {
         get
         {
                   String filter=' and KAName__c=\''+KASelectedValue+'\' and Type__c=\'FG\'';   
               return getCommonMethod.LoadResourceAllcationListByCity(filter,RecordId);
         }
     }
   public String RecordId
   {
       get
       {
           if(System.currentPageReference().getParameters().get('id')!=NULL)
               return System.currentPageReference().getParameters().get('id').substring(0,15);  
          else
              return null;
       }
       set;
   }
    //获取当前参与列表
      public List<ParticipatorArea__c> getParticipatorAreaList
      {
          get
          {
              return [select id,KA_Status__c from ParticipatorArea__c where Activity_Name__c=:RecordId and KA__c=:KASelectedValue];
          }
      }
       //设置KA状态，控制按钮是否可见
     public void SetKAStatus()
     {
         if(ActivityInit.Activity_Stage__c=='活动已取消')
         {
             WhetherDisplaySubmitOrSaveButtonOrNot=false;
         }
         else
         {
             Date StartDT=ActivityInit.Activity_Start_Date__c;     
             if(Date.today()>= StartDT.addDays(-21))//开始活动前21天不可以调时间
            {  
                WhetherDisplaySubmitOrSaveButtonOrNot=false;
             }
             else
             {
                             //         System.assert(false,getParticipatorAreaList);              
                 if(getParticipatorAreaList!=NULL && getParticipatorAreaList.size()>0)
                 {
                       if(getParticipatorAreaList[0].KA_Status__c == '已审批' || getParticipatorAreaList[0].KA_Status__c=='KAM已提交')          
                          WhetherDisplaySubmitOrSaveButtonOrNot=false;
                       else
                           WhetherDisplaySubmitOrSaveButtonOrNot=true; 
                  }
                  else
                  {
                      WhetherDisplaySubmitOrSaveButtonOrNot=false;
                  }
             }
          }
     }
    public KAForKAResourceAllcationController (ApexPages.StandardController controller)
     {
        InitReLoadAllData();
     }
     public void  InitReLoadAllData()//初始化数据
     {
     //获取用户管辖的KA
         
        getCommonMethod=new CommonMethod();
        KAList=getCommonMethod.UserKAOptionList();
        if(KASelectedValue==NULL)
            KASelectedValue=KAList[0].getValue();
             
         getCommonMethod=new CommonMethod();
         ETresourceDetailList=new List<CityResourceAllcation__c>();
         FGresourceDetailList=new List<CityResourceAllcation__c>();
         WhetherDisplaySubmitOrSaveButtonOrNot=true;
          
        
         PlaceAttribute=new CommonAttribute();
         ActivityInit=[Select Id,Name,  Activity_End_Date__c, Activity_Notice__c, Activity_Stage__c, Activity_Start_Date__c, 
                             Activity_Type_State__c, Activity_Type__c, DM_End_Date__c, DM_Start_Date__c, Display_End_Date__c, 
                             Display_Start_Date__c,Serial_Number__c FROM Activity_Information__c where id=: RecordId];
          
            SetKAStatus();
            LoadOutletList();
            TotalMoney=TotalMoneyByKA();
     }
          //按KA汇总金额
     public decimal TotalMoneyByKA()
     {
         List<AggregateResult>TotalNumberList=[select sum(Money__c) totalNumber from Activity_Competition_Brand_Detail__c where ActivityId__c=:RecordId and Participator_Detail_Outlet__r.KA__c=:KASelectedValue];
         if(TotalNumberList[0].get('totalNumber')!=NULL)
             return decimal.valueOf((Double)TotalNumberList[0].get('totalNumber'));
         else
             return 0;
     }
     
     public PageReference LoadNewOutlet()
     {
        // getCommonMethod.GenerateNewOutlet(RecordId,1);//加载新增的门店
         return null;
     }
     public void LoadOutletList()
     {
           //加载竞品
         if(CompetitionBrandList==NULL)
                 CompetitionBrandList=new List<ActivityCompetitionBrandEntry>();
         else
                CompetitionBrandList.clear();
            for(Activity_Competition_Brand_Information__c acb:[Select  Name, Activity_Information__c, Type__c, Competition_Cost_Source__c, Competition_Cost_Type__c,
                                                 Competition_Promotion_Type__c FROM Activity_Competition_Brand_Information__c 
                                                 where Activity_Information__c=:RecordId 
                                                 and KA__c=:KASelectedValue
                                                 ])
            {
                CompetitionBrandList.add(new ActivityCompetitionBrandEntry(false,acb));
            }
             
        if(KASelectedValue==NULL)
            KASelectedValue=KAList[0].getValue();
         String filter=' and KAName__c=\''+KASelectedValue+'\'';

         List<CityResourceAllcation__c> resourceDetailList=new List<CityResourceAllcation__c>();
         resourceDetailList=getCommonMethod.LoadCityList(filter,RecordId);//加载门店列表
         ETresourceDetailList.clear();
         FGresourceDetailList.clear();
         //System.assert(false,resourceDetailList);
         for(CityResourceAllcation__c rad:resourceDetailList){
             if(rad.Type__c=='ET')
                ETresourceDetailList.add(rad);
             else if(rad.Type__c=='FG') 
                FGresourceDetailList.add(rad);
        }
   
         ColumnETList=getCommonMethod.GetDynamicETColumnList(ETresourceDetailList);//获取ET列名
         ColumnFGList=getCommonMethod.GetDynamicETColumnList(FGresourceDetailList);//获取FG列名
         ETDynamicColumnEntryList=getCommonMethod.GetDynamicEntryList(ETresourceDetailList);//获取ET门店列表
         FGDynamicColumnEntryList=getCommonMethod.GetDynamicEntryList(FGresourceDetailList);//获取FG门店列表
         QueryCompetitionList();//加载竞品
     }
     
      //添加竞品信息
     public PageReference addCompetitionBrandAction()
     {
         if(CompetitionBrandList==NULL)
             CompetitionBrandList=new  List<ActivityCompetitionBrandEntry>();
             //try
            // {
                 if(PlaceAttribute.KAPromotionTypeSelectedValue=='' || PlaceAttribute.KAPromotionTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竟品促销形式');
                 if(PlaceAttribute.KACostTypeSelectedValue=='' || PlaceAttribute.KACostTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用形式');
                  if(PlaceAttribute.CostSourceSelectedValue=='' || PlaceAttribute.CostSourceSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用来源');
                  if(CompetitionBrandList.size()>=8)
                      throw new CustomException ('竞品类型不能大于8个！');        
                    //如果添加重复的竞品信息则返回空  
                   for(ActivityCompetitionBrandEntry entry:CompetitionBrandList)   
                   {
                       if(entry.ActivityCompetitionMsg.Competition_Cost_Source__c==PlaceAttribute.CostSourceSelectedValue &&
                          entry.ActivityCompetitionMsg.Competition_Cost_Type__c== PlaceAttribute.KACostTypeSelectedValue&&
                          entry.ActivityCompetitionMsg.Competition_Promotion_Type__c==PlaceAttribute.KAPromotionTypeSelectedValue)
                            throw new CustomException ('该竞品类型已被选择！');   
                   }
                    Activity_Competition_Brand_Information__c activity=new Activity_Competition_Brand_Information__c(Activity_Information__c=RecordId,
                                                                                                  Competition_Cost_Source__c=PlaceAttribute.CostSourceSelectedValue,
                                                                                                  Competition_Cost_Type__c=PlaceAttribute.KACostTypeSelectedValue,
                                                                                                   Competition_Promotion_Type__c=PlaceAttribute.KAPromotionTypeSelectedValue,
                                                                                                   KA__c=KASelectedValue);
                                                                                                   // Type__c='KA' 
                                                                                     
                   CompetitionBrandList.add(new ActivityCompetitionBrandEntry(false,activity));
                   
                   insert activity;
                 List<Activity_Competition_Brand_Detail__c> competitionDetail=new List<Activity_Competition_Brand_Detail__c>(); 
                 Set<Id> IdList=new Set<Id>(); 
                 for(Participator_Detail_Outlet__c par: [select id,Outlet_Name__c,OwnerId from Participator_Detail_Outlet__c where ActivityId__c=:RecordId and KA__c=:KASelectedValue
                                                                               ])
                 {
                    if(!IdList.contains(par.Outlet_Name__c)){
                       IdList.add(par.Outlet_Name__c);
                       Activity_Competition_Brand_Detail__c acbd;
                       if(activity.Competition_Promotion_Type__c=='陈列租金')
                     {
                         acbd=new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=activity.id,
                                                                                                     Start_Date__c=ActivityInit.Display_Start_Date__c,
                                                                                                     End_Date__c=ActivityInit.Display_End_Date__c,      
                                                                                                     Participator_Detail_Outlet__c=par.Id,OwnerId=par.OwnerId);
                      }
                      else if(activity.Competition_Promotion_Type__c=='海报')
                      {
                          acbd=new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=activity.id,
                                                                                                     Start_Date__c=ActivityInit.DM_Start_Date__c,
                                                                                                     End_Date__c=ActivityInit.DM_End_Date__c,      
                                                                                                     Participator_Detail_Outlet__c=par.Id,OwnerId=par.OwnerId);
                      }
                      else
                      {
                          acbd=new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=activity.id,
                                                                                                     Participator_Detail_Outlet__c=par.Id,OwnerId=par.OwnerId);
                      }
                        competitionDetail.add(acbd);
                    }                         
                 }         
                 insert competitionDetail;
                  
          //  }
          //   catch(Exception ex)
         //   {
          //        ApexPages.addMessages(ex);
           //      return null;
         //   }
                 
             PlaceAttribute.KAPromotionTypeSelectedValue='';
             PlaceAttribute.KACostTypeSelectedValue='';
             PlaceAttribute.CostSourceSelectedValue='';
             return null;
     }
   
     
      public PageReference DeleteCompetitionBrandAction()
      {
         for(Integer i=0;i<CompetitionBrandList.size();i++)
         {
              ActivityCompetitionBrandEntry entry=CompetitionBrandList[i];
             if(entry.IsCheck)
             {
                 CompetitionBrandList.remove(i);
                 delete [select id from Activity_Competition_Brand_Detail__c where Activity_Competition_Brand_Information__c=:entry.ActivityCompetitionMsg.Id];
                 delete [select id from Activity_Competition_Brand_Information__c where id=:entry.ActivityCompetitionMsg.Id];
                 i--;
             }
         }
         TotalMoneyByKA();
         QueryCompetition();
          return null;
      }
      public PageReference QueryCompetition()
      {
          QueryCompetitionList();
          return null;
      }
      public void QueryCompetitionList()
      {
          String filter=' and Participator_Detail_Outlet__r.KA__c=\''+KASelectedValue+'\'';
         // String filter='';
          if(PlaceAttribute.RegionSelectedValue != NULL && PlaceAttribute.RegionSelectedValue != '0')
              filter+=' and OutletRegion__c=\''+PlaceAttribute.RegionSelectedValue+'\'';
          if(PlaceAttribute.SubRegionSelectedValue!=NULL && PlaceAttribute.SubRegionSelectedValue!='0')
          {
              filter+=' and  OutletSubregion__c=\''+PlaceAttribute.SubRegionSelectedValue+'\'';
          }
          if(PlaceAttribute.AreaSelectedValue!=NULL && PlaceAttribute.AreaSelectedValue!='0')
          {
              filter+=' and OutletArea__c=\''+PlaceAttribute.AreaSelectedValue+'\'';
          }
          if(PlaceAttribute.CitySelectedValue!=NULL && PlaceAttribute.CitySelectedValue!='0')
          {
              filter+=' and OutletCity__c=\''+PlaceAttribute.CitySelectedValue+'\'';
          }
          if(CompetitorOtletName!=NULL && CompetitorOtletName!='' )
          {
              filter+=' and OutletName__c=\''+CompetitorOtletName+'\'';
          }
           if(PlaceAttribute.OutletTypeSelectedValue!=NULL && PlaceAttribute.OutletTypeSelectedValue!='')
          {
             
              filter+=' and OutletType__c=\''+PlaceAttribute.OutletTypeSelectedValue+'\'';
          }
           if(PlaceAttribute.ChannelSelectedValue!=NULL && PlaceAttribute.ChannelSelectedValue!='')
          {
              filter+=' and OutletChannel__c=\''+PlaceAttribute.ChannelSelectedValue+'\'';
          }
              //添加的竞品条件
            if(SSYPromotionTypeSelectedValue!=NULL && SSYPromotionTypeSelectedValue!='')
          {
              filter+=' and Promotion_Type__c=\''+SSYPromotionTypeSelectedValue+'\'';
          }
             if(SSYKACostTypeSelectedValue!=NULL && SSYKACostTypeSelectedValue!='')
          {
              filter+=' and Cost_Type__c=\''+SSYKACostTypeSelectedValue+'\'';
          }
             if(CostSourceSelectedValue!=NULL && CostSourceSelectedValue!='')
          {
              filter+=' and Competition_Cost_Source__c=\''+CostSourceSelectedValue+'\'';
          }
          string sql='select id,OutletName__c,Display_Type__c ,Competition_Cost_Source__c,Cost_Type__c,Promotion_Type__c,'+
                          ' Money__c,End_Date__c,Start_Date__c from  Activity_Competition_Brand_Detail__c'+
                          '  where ActivityId__c=\''+RecordId+'\'';  
          if(filter!='')
              sql+=filter;
        //      throw new CustomException (sql);
      
         CompetitionBrandDetailList=Database.query(sql);
      }
      public PageReference QueryOutletList()//按门店查询
      {   
          CompetitionBrandList.clear();
          CompetitionBrandDetailList.clear();
          SetKAStatus();
          LoadOutletList();
          TotalMoney=TotalMoneyByKA();
          return null;
      }
      public PageReference SaveActivity()
      {
          //验证，设置竞品投入资料中，若金额不为空，则必须填入开始时间和结束时间
         try{
            for(Activity_Competition_Brand_Detail__c abd:CompetitionBrandDetailList){
            if((abd.Money__c!=null || abd.Start_Date__c!=null || abd.End_Date__c!=null) && abd.Competition_Cost_Source__c!='合同内费用'){ 
                if(abd.Promotion_Type__c=='陈列租金'){
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null || abd.Display_Type__c==null)
                       throw new CustomException ('设置了金额，则开始时间和结束时间不能为空,并且是陈列租金形式的必须选择陈列形式！');
                }else{
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null)
                      throw new CustomException ('设置了金额，则开始时间和结束时间不能为空！');
                }
             }else{
                if((abd.Start_Date__c!=null && abd.End_Date__c==null) || (abd.Start_Date__c==null && abd.End_Date__c!=null))
                      throw new CustomException ('设置了金额，请认真填写开始时间和结束时间！');
             }   
               if(abd.Start_Date__c!=null && abd.End_Date__c!=null){
                 if(abd.Start_Date__c>abd.End_Date__c)
                   throw new CustomException ('开始时间不能大于结束时间！');
            } 
           }
          }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
         SaveData();
       //  InitReLoadAllData();
        pageReference pr = new pageReference('/'+ActivityInit.id);     
        pr.setredirect(true);   
        return pr;
      }
      public PageReference SubmitActivity()
      {
            //验证，设置竞品投入资料中，若金额不为空，则必须填入开始时间和结束时间
         try{
          for(Activity_Competition_Brand_Detail__c abd:CompetitionBrandDetailList){
           if((abd.Money__c!=null || abd.Start_Date__c!=null || abd.End_Date__c!=null) && abd.Competition_Cost_Source__c!='合同内费用'){ 
                if(abd.Promotion_Type__c=='陈列租金'){
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null || abd.Display_Type__c==null)
                       throw new CustomException ('设置了金额，则开始时间和结束时间不能为空,并且是陈列租金形式的必须选择陈列形式！');
                }else{
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null)
                      throw new CustomException ('设置了金额，则开始时间和结束时间不能为空！');
                }
             }else{
                if((abd.Start_Date__c!=null && abd.End_Date__c==null) || (abd.Start_Date__c==null && abd.End_Date__c!=null))
                      throw new CustomException ('设置了金额，请认真填写开始时间和结束时间！');
             }   
               if(abd.Start_Date__c!=null && abd.End_Date__c!=null){
                 if(abd.Start_Date__c>abd.End_Date__c)
                   throw new CustomException ('开始时间不能大于结束时间！');
            } 
            
           }
          }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
         for(ParticipatorArea__c par: getParticipatorAreaList){
             par.KA_Status__c='KAM已提交'; 
             update par;//更新KA提交状态
             }     
        SaveActivity();
        WhetherDisplaySubmitOrSaveButtonOrNot=false;
        //发送邮件到总部,总部审批KA资源分配
        List<string> EmailList=new List<string>();
        EmailList=getCommonMethod.getUserEmailAddress('NTMKT',RecordId);
        if(EmailList.size()>0){
            User u=getCommonMethod.getUserInfo();
            String BodyString=u.Name+'已提交了【'+ActivityInit.Name+'】活动的资源调整和竞品添加,请登陆凤凰系统进行相应的审批工作,谢谢！';
            String subject='审批【'+ActivityInit.Name+'】活动中待审批的KAM';
            EmailHander.SendMail(BodyString,EmailList,subject,'',null);  
        }
      
        pageReference pr = new pageReference('/'+RecordId);     
        pr.setredirect(true);   
        return pr; 
      }
      public void SaveData()
      { 
         Activity_Information__c ActivityStatus=[select IsCompleted__c from Activity_Information__c where id=:RecordId];
      //   if(ActivityStatus.IsCompleted__c)
      //   {
             //先删除
          delete [select id from CityResourceAllcation__c where Activity_Information__c=:RecordId and KAName__c=:KASelectedValue];
              //重新保存城市分配量
           getCommonMethod.SaveCityResourceAllocation('ET',RecordId,KASelectedValue,NULL,ActivityInit.Activity_Type__c,ETDynamicColumnEntryList);
           getCommonMethod.SaveCityResourceAllocation('FG',RecordId,KASelectedValue,NULL,ActivityInit.Activity_Type__c,FGDynamicColumnEntryList);
             //分配给相应的门店
         
         //update ActivityInit;//更新活动
         if(CompetitionBrandDetailList!=null)
             update CompetitionBrandDetailList;//更新竞品
    //  }
    }     
    
    public PageReference RedirectCityAllocationUploadFilePage()
     {
      //   if(WhetherDisplaySubmitOrSaveButtonOrNot)
     //    {
             PageReference pf=new PageReference('/apex/KAUploadResourceFile?id='+RecordId+'&&type=CityAllocation');
             pf.setRedirect(true);
             return pf;
      //   }
         return null;
     }
      public PageReference RedirectCompetitionUploadFilePage()
     {
      //   if(WhetherDisplaySubmitOrSaveButtonOrNot)
             PageReference pf=new PageReference('/apex/KAUploadResourceFile?id='+RecordId+'&&type=Competition');
             pf.setRedirect(true);
             return pf;
      //   }
         return null;
     }
      public PageReference  FillCompetitionList()
      {
          for(Activity_Competition_Brand_Detail__c acbd:CompetitionBrandDetailList)
          {
              acbd.Start_Date__c=ActivityInit.Activity_Start_Date__c;
              acbd.End_Date__c=ActivityInit.Activity_End_Date__c;
          }
          return null;
      } 
   
}